﻿using System;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace LenderClearingHouse
{
  public partial class PropertyDetails : PageBase
  {
    protected SourcePage SourcePage
    {
      get { return (SourcePage)Session["SourcePage"]; }
    }

    bool Editable
    {
      get
      {
        return CurrentUser.UserRole == UserRole.SuperAdmin
        || (SourcePage == SourcePage.LvreoList && CurrentUser.LvreoRole == RoleAccess.ReadWrite)
        || (SourcePage == SourcePage.SdreoList && CurrentUser.SdreoRole == RoleAccess.ReadWrite);
      }
    }

    public const string STR_WE_ARE_ON_DETAILS = "STR_WE_ARE_ON_DETAILS";

    protected void Page_Load(object sender, EventArgs e)
    {
      Session[STR_WE_ARE_ON_DETAILS] = "1";

      if (IsPostBack) return;

      panelUpload.Visible = Editable;

      RefreshImages();
      RefreshDocuments();

      string location = "";
      string details = "";
      GetPropertyInfo(out location, out details);
      lbAddress.Text = location;
      lbDetails.Text = details;
    }

    string PropertyImagesFolder
    {
      get
      {
        switch (SourcePage)
        {
          case SourcePage.MasterList:
          case SourcePage.WorkingList:
            return "~/DocSecure/PropertyImages/";
          case SourcePage.LvreoList: return "~/DocSecure/LVREO/PropertyImages/";
          case SourcePage.SdreoList: return "~/DocSecure/SDREO/PropertyImages/";
          default: throw new Exception();
        }
      }
    }

    string PropertyDocumentsFolder
    {
      get
      {
        switch (SourcePage)
        {
          case SourcePage.MasterList:
          case SourcePage.WorkingList:
            return "~/DocSecure/PropertyDocuments/";
          case SourcePage.LvreoList: return "~/DocSecure/LVREO/PropertyDocuments/";
          case SourcePage.SdreoList: return "~/DocSecure/SDREO/PropertyDocuments/";
          default: throw new Exception();
        }
      }
    }

    string GetImagesSP
    {
      get
      {
        switch (SourcePage)
        {
          case SourcePage.MasterList:
          case SourcePage.WorkingList:
            return "getPropertyImages";
          case SourcePage.LvreoList: return "getLvreo_PropertyImages";
          case SourcePage.SdreoList: return "getSdreo_PropertyImages";
          default: throw new Exception();
        }
      }
    }

    string GetDocumentsSP
    {
      get
      {
        switch (SourcePage)
        {
          case SourcePage.MasterList:
          case SourcePage.WorkingList:
            return "getPropertyDocs";
          case SourcePage.LvreoList: return "getLvreo_PropertyDocs";
          case SourcePage.SdreoList: return "getSdreo_PropertyDocs";
          default: throw new Exception();
        }
      }
    }

    string DeleteDocumentSP
    {
      get
      {
        switch (SourcePage)
        {
          case SourcePage.MasterList:
          case SourcePage.WorkingList:
            return "deletePropertyDoc";
          case SourcePage.LvreoList: return "deleteLvreo_PropertyDoc";
          case SourcePage.SdreoList: return "deleteSdreo_PropertyDoc";
          default: throw new Exception();
        }
      }
    }

    string DeleteImageSP
    {
      get
      {
        switch (SourcePage)
        {
          case SourcePage.MasterList:
          case SourcePage.WorkingList:
            return "deletePropertyImage";
          case SourcePage.LvreoList: return "deleteLvreo_PropertyImage";
          case SourcePage.SdreoList: return "deleteSdreo_PropertyImage";
          default: throw new Exception();
        }
      }
    }

    string InsertDocumentSP
    {
      get
      {
        switch (SourcePage)
        {
          case SourcePage.MasterList:
          case SourcePage.WorkingList:
            return "insertPropertyDoc";
          case SourcePage.LvreoList: return "insertLvreo_PropertyDoc";
          case SourcePage.SdreoList: return "insertSdreo_PropertyDoc";
          default: throw new Exception();
        }
      }
    }

    string InsertImageSP
    {
      get
      {
        switch (SourcePage)
        {
          case SourcePage.MasterList:
          case SourcePage.WorkingList:
            return "insertPropertyImage";
          case SourcePage.LvreoList: return "insertLvreo_PropertyImage";
          case SourcePage.SdreoList: return "insertSdreo_PropertyImage";
          default: throw new Exception();
        }
      }
    }

    void GetPropertyInfo(out string location, out string details)
    {      
      string spName = null;
      location = "";
      details = "";

      switch (SourcePage)
      {
        case SourcePage.MasterList:
              spName = "getPropertyInfo"; break;
        case SourcePage.WorkingList:          
              spName = "getPropertyInfoWorkingList"; break;
        case SourcePage.LvreoList: spName = "getLvreo_PropertyInfo"; break;
        case SourcePage.SdreoList: spName = "getSdreo_PropertyInfo"; break;
        default: throw new Exception();
      }

      DataAccess da = new DataAccess();
      DataTable dt = da.ExecuteSQL(string.Format("{0} {1}", spName, PropertyId));
      if (dt.Rows.Count == 0) return;

      location = dt.Rows[0]["Location"].ToString();
      details = dt.Rows[0]["PropertyDetails"].ToString();
    }

    private void RefreshImages()
    {
      phItems.Controls.Clear();
      DataAccess da = new DataAccess();
      DataTable tbl = da.ExecuteSQL(string.Format("{0} {1}", GetImagesSP, PropertyId));      

      foreach (DataRow dr in tbl.Rows)
      {
        HtmlImage img = new HtmlImage();
        img.Src = GetFullImageUrl(dr["ImagePath"].ToString());

        phItems.Controls.Add(img);
      }

      dlImages.DataSource = tbl;
      dlImages.DataBind();
    }

    string GetFullImageUrl(string imagePath)
    {
      return ResolveClientUrl(PropertyImagesFolder) + imagePath;
    }

    string PropertyId
    {
      get { return Request.QueryString["propertyId"]; }
    }

    private void RefreshDocuments()
    {
      DataAccess da = new DataAccess();
      dlDocuments.DataSource = da.ExecuteSQL(string.Format("{0} {1}", GetDocumentsSP, PropertyId));
      dlDocuments.DataBind();
    }

    protected void dlDocuments_ItemDataBound(object sender, DataListItemEventArgs e)
    {
      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
      {
        DataRowView rowView = e.Item.DataItem as DataRowView;

        var hlLink = e.Item.FindControl("hlLink") as HyperLink;
        hlLink.NavigateUrl =
          string.Format(PropertyDocumentsFolder + "{0}",
          HttpUtility.UrlEncode(rowView["DocumentPath"].ToString().Trim())).Replace("+", "%20");
        hlLink.Text = rowView["DocumentPath"].ToString();

        var delBtn = e.Item.FindControl("btnDeleteDocument") as ImageButton;
        delBtn.Visible = Editable;
        delBtn.CommandArgument = rowView["DocId"].ToString() + ";" + rowView["DocumentPath"].ToString().Trim();
      }
    }

    protected void dlDocuments_ItemCommand(object source, DataListCommandEventArgs e)
    {
      if (e.CommandName == "DeleteDocument")
      {
        string docId = e.CommandArgument.ToString().Split(';')[0];
        string docPath = e.CommandArgument.ToString().Split(';')[1];

        DataAccess da = new DataAccess();
        da.ExecuteSQLNonQuery(string.Format("{0} {1}", DeleteDocumentSP, docId));

        File.Delete(Path.Combine(Server.MapPath(PropertyDocumentsFolder), docPath));

        RefreshDocuments();
      }
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
      DataAccess da = new DataAccess();

      foreach (UploadedFile uf in upload.UploadedFiles)
      {
        string newFileName = PropertyId + " " + uf.GetName();

        if (uf.GetExtension().Contains("pdf"))
        {
          File.Copy(
            Path.Combine(Server.MapPath(upload.TargetFolder), uf.GetName()),
            Path.Combine(Server.MapPath(PropertyDocumentsFolder), newFileName), true);
          da.ExecuteSQLNonQuery(
            string.Format("{0} {1}, '{2}'", InsertDocumentSP, PropertyId, newFileName));
        }
        else
        {
          string newFullFileName =
            Path.Combine(Server.MapPath(PropertyImagesFolder), newFileName);

          File.Copy(
            Path.Combine(Server.MapPath(upload.TargetFolder), uf.GetName()),
            newFullFileName, true);

          ResizeImage(newFullFileName, newFullFileName, 540, 330, false);
          
          da.ExecuteSQLNonQuery(
            string.Format("{0} {1}, '{2}'", InsertImageSP, PropertyId, newFileName));
        }
      }

      lbDocumentsUploaded.Text =
        string.Format("{0} file(s) uploaded", upload.UploadedFiles.Count);

      RefreshDocuments();
      RefreshImages();
    }

    public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
    {
      System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

      // Prevent using images internal thumbnail
      FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
      FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

      if (OnlyResizeIfWider)
      {
        if (FullsizeImage.Width <= NewWidth)
        {
          NewWidth = FullsizeImage.Width;
        }
      }

      int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
      if (NewHeight > MaxHeight)
      {
        // Resize with height instead
        NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
        NewHeight = MaxHeight;
      }

      System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

      // Clear handle to original file so that we can overwrite it if necessary
      FullsizeImage.Dispose();

      // Save resized picture
      NewImage.Save(NewFile);
    }

    protected void dlImages_ItemDataBound(object sender, DataListItemEventArgs e)
    {
      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
      {
        DataRowView rowView = e.Item.DataItem as DataRowView;

        var imgImage = e.Item.FindControl("imgImage") as Image;
        imgImage.ImageUrl = GetFullImageUrl(rowView["ImagePath"].ToString().Trim());

        var delBtn = e.Item.FindControl("btnDeleteImage") as ImageButton;
        delBtn.Visible = Editable;
        delBtn.CommandArgument = rowView["ImageId"].ToString() + ";" + rowView["ImagePath"].ToString().Trim();
      }
    }

    protected void dlImages_ItemCommand(object source, DataListCommandEventArgs e)
    {
      string imageId = e.CommandArgument.ToString().Split(';')[0];
      string imagePath = e.CommandArgument.ToString().Split(';')[1];

      DataAccess da = new DataAccess();
      da.ExecuteSQLNonQuery(string.Format("{0} {1}", DeleteImageSP, imageId));

      File.Delete(Path.Combine(Server.MapPath(PropertyImagesFolder), imagePath));

      RefreshImages();
    }
  }
}